import './index.scss'
import React, { useState, useEffect, useRef } from 'react'
import { Line } from '@ant-design/plots';
import { createRoot } from 'react-dom/client'
import { Link, useNavigate } from 'react-router-dom'
import { Card, Breadcrumb, Input, message, ConfigProvider, Tooltip, Modal, Col, Row, Form, Button, Radio, DatePicker, Checkbox, Popconfirm, Empty } from 'antd'
import locale from 'antd/es/date-picker/locale/zh_CN'
import { Table, Tag, Space } from 'antd'
import { EditOutlined, DeleteOutlined } from '@ant-design/icons'
import useUserList from '@/hooks/useUserList'
// import AddUser from './addUser'
import { userRegister, GetUserinfo, UserEdit } from '@/apis/user';
import { format } from "date-fns"

const { RangePicker } = DatePicker
const UserList = () => {
    //userinfo hook
    const { authentication, checkboxList, count, reqData, userInfoList, userToken, onPageChange, onConfirm, onFinish, getList } = useUserList()
    //定义枚举状态 
    const permission_status = {
        true: <Tag color="green">有</Tag>,
        false: <Tag color="default">无</Tag>
    }
    //表单重置
    const [form] = Form.useForm()

    //修改数据
    const [loading, setLoading] = useState(false)
    const [open, setOpen] = useState(false)
    //数据状态
    const [userState, setUserState] = useState(false)
    //表单重置
    const [form2] = Form.useForm()

    const cardRef = useRef(null); // 获取 Card 的 DOM 元素
    const rowRef = useRef(null); // 获取 Row 的 DOM 元素
    const [tableheight, setTableHeight] = useState(200); // 存储 Row 高度
    // 获取卡片高度
    useEffect(() => {
        const observer = new ResizeObserver((entries) => {
            //console.log(cardRef.value)
            if (cardRef.current) {
                for (const entry of entries) {
                    // 3. 获取最新高度并更新状态
                    // console.log(1)
                    const Cardheight = Math.round(entry.contentRect.height) // 获取卡片高度
                    // const Rowheight = rowRef.current.clientHeight; // 获取 Row 高度
                    const height = Math.floor(Cardheight - 180)
                    // console.log(height)
                    setTableHeight(height)
                }
            }
        });
        // 开始观察
        observer.observe(cardRef.current);
        // 4. 组件卸载时断开监听
        return () => {
            if (cardRef.current) {
                observer.unobserve(cardRef.current);
            }
        };
    }, []);


    useEffect(() => {
        const DemoLine = () => {
            const data = (userInfoList.map(item => {
                const formatted = format(new Date(item.create_time), "yyyy-MM-dd")// 只保留前10位 YYYY-MM-DD
                return {
                    ...item,
                    create_time: formatted,
                };
            })).reverse();

            const config = {
                data,
                xField: 'create_time',
                yField: 'tokenCont',
                point: {
                    shapeField: 'square',
                    sizeField: 2,
                },
                interaction: {
                    tooltip: {
                        marker: false,
                    },
                },
                style: {
                    lineWidth: 1,
                },
            };
            return <Line {...config} />;
        };
        createRoot(document.getElementsByClassName('container')[0]).render(<DemoLine />);
    }, [userInfoList])
    // //显示弹窗
    // const showModal = async (id) => {
    //     // if (authentication.code != 200) {
    //     //     message.error(authentication.message)
    //     //     return
    //     // }
    //     setOpen(true)
    //     form2.setFieldsValue({ id: '', sp_role: '', permission: [], msg: '', passwd: '' })
    //     if (id == "") {
    //         setUserState(false)
    //     }
    //     else {
    //         setUserState(true)
    //         const res = await GetUserinfo(id)
    //         // console.log(res)
    //         form2.setFieldsValue({ ...res.data, sp_role: res.data.login_name })
    //     }
    // };
    //添加数据
    // const handleOk = async () => {
    //     try {
    //         setLoading(true)
    //         const formdata = await form2.validateFields()
    //         const { id, msg, permission, sp_role, passwd } = formdata
    //         const data = {
    //             id,
    //             sp_role,
    //             permission,
    //             msg,
    //             passwd
    //         }
    //         var res = ""
    //         if (id == "")
    //             //添加
    //             res = await userRegister(data)
    //         else {
    //             //修改
    //             res = await UserEdit(data)
    //         }

    //         if (res.code == 200) {
    //             setOpen(false)
    //             getList()
    //             if (userState == true) {
    //                 message.success('修改成功')
    //             }
    //             else {
    //                 message.success('添加成功')
    //             }
    //         }
    //         else {
    //             message.error(res.message)
    //         }
    //     } catch (error) {
    //         message.error('请填写完整的表单！')
    //     }
    //     setLoading(false)
    // };
    // const handleCancel = () => {
    //     setOpen(false)
    // }

    // 准备列数据
    const columns = [
        {
            title: 'id',
            dataIndex: 'id',
            width: 30,
            hidden: true
        },
        {
            title: '用户名',
            dataIndex: 'username',
            // render: cover => {
            //     return <img src={cover.images[0] || img404} width={80} height={60} alt="" />
            // }
        },
        {
            title: 'token使用量',
            dataIndex: 'tokenCont',
        },
        // {
        //     title: 'Key',
        //     // width: 400,
        //     dataIndex: 'key',
        //     ellipsis: {
        //         showTitle: false,
        //     },
        //     render: (msg) => (
        //         <Tooltip styles=
        //             {{
        //                 root: {
        //                     maxWidth: '600px', // 设置最大宽度
        //                     whiteSpace: 'normal', // 允许换行
        //                 }
        //             }}
        //             placement="topLeft" title={msg}>
        //             {msg}
        //         </Tooltip>
        //     ),
        // },
        {
            title: '时间',
            dataIndex: 'create_time',
            render: (ceate_time) => {
                if (ceate_time) {
                    return format(new Date(ceate_time), "yyyy-MM-dd")
                }
            }
        },
        // {
        //     title: '操作',
        //     render: data => {
        //         return (
        //             <Space size="middle">

        //                 {/* <Button type="primary" shape="circle" onClick={() => showModal(`${data.id}`)} icon={<EditOutlined />} /> */}
        //                 <Popconfirm
        //                     title="删除用户"
        //                     description="确定要删除当前用户吗?"
        //                     onConfirm={() => { onConfirm(data.id) }}
        //                     // onCancel={cancel}
        //                     okText="是"
        //                     cancelText="否"
        //                     key={2}
        //                 >
        //                     <Button
        //                         type="primary"
        //                         danger
        //                         shape="circle"
        //                         icon={<DeleteOutlined />}
        //                     />
        //                 </Popconfirm>
        //             </Space>
        //         )
        //     }
        // }
    ]

    return (
        <div style={{ height: "100%", display: "flex", flexDirection: "column" }}>
            <Card
                // title={
                //     <Breadcrumb items={[
                //         { title: <Link to={'/'}>首页</Link> },
                //         { title: 'Tokens用量' },
                //     ]} />
                // }
                style={{ marginBottom: 5 }}
            >

                <Form initialValues={{ permission: '' }} form={form} onFinish={val => onFinish(val)}>
                    <Row gutter={24}>
                        {/* <Col span={6} key={1}>
                            <Form.Item label="用户名" name="_sp_role">
                                <Input placeholder="" />
                            </Form.Item>
                        </Col> */}
                        <Col span={10} key={2}>
                            <Form.Item label="添加时间" name="ceate_time">
                                <RangePicker locale={locale}></RangePicker>
                            </Form.Item>
                        </Col>
                        <Col span={6} key={7}>

                            <Form.Item>
                                <Button type="primary" htmlType="submit" style={{ marginLeft: 40 }}>
                                    筛选
                                </Button>
                                <Button style={{ marginLeft: "20px" }} htmlType="Reset" >
                                    重置
                                </Button>
                            </Form.Item>
                        </Col>
                    </Row>
                </Form>
                <div style={{ height: "180px" }} className='container'></div>
            </Card>
            <div style={{ height: "100%", overflow: "hidden" }}>

                <Card title={`根据筛选条件共查询到 ${count} 条结果，token总数：${userToken?.token || 0}，token总使用量：${userToken?.tokenUsage || 0}，使用率：${userToken?.tokenusagerate || 0}`} ref={cardRef} style={{ tableLayout: "fixed", height: "100%", padding: '10px' }}>
                    {/* <AddUser getList={getList} /> */}
                    {/* <Row justify="start" className='RowPadd' ref={rowRef}>
                        <Col >
                            <Button  type="primary">添加</Button>
                        </Col>
                    </Row> */}
                    {/* <Modal
                        open={open}
                        title={userState ? "修改用户" : "'添加用户"}
                        onOk={handleOk}
                        onCancel={handleCancel}
                        width={600}
                        centered={true}
                        footer={[
                            <Button type="primary" key="submit" loading={loading} onClick={handleOk}>
                                {userState ? "修改" : "添加"}
                            </Button>,
                            <Button
                                type="primary"
                                key="close"
                                onClick={handleCancel}
                            >
                                关闭
                            </Button>,
                        ]}
                    >
                        <div style={{ padding: "40px", paddingBottom: "5px" }}>
                            <Form form={form2} initialValues={{ permission: 0 }} >
                                <Form.Item label="id" name="id" hidden={true}>
                                    <Input placeholder="" />
                                </Form.Item>
                                <Form.Item label="用户名" name="sp_role"
                                    rules={[
                                        {
                                            required: true,
                                            message: '请输入用户名',
                                        },
                                    ]}>
                                    <Input placeholder="" />
                                </Form.Item>
                                <Form.Item label="密码" name="passwd">
                                    <Input.Password size="large" placeholder="" />
                                </Form.Item>
                                <Form.Item
                                    name="msg"
                                    label="详细信息"
                                    rules={[
                                        {
                                            // required: true,
                                            message: 'Please input msg',
                                        },
                                    ]}
                                >
                                    <Input.TextArea showCount style={{ height: "120px" }} />
                                </Form.Item>
                            </Form>
                        </div>
                    </Modal> */}
                    <ConfigProvider
                        locale={{
                            Pagination: {
                                items_per_page: ' / 页', // 👈 改这里
                                showSizeChanger: true,
                            },
                        }}
                    >
                        <Table
                            rowKey="create_time"
                            columns={columns}
                            dataSource={userInfoList}
                            scroll={{ y: tableheight }}
                            locale={{
                                emptyText: (
                                    <Empty
                                        image={Empty.PRESENTED_IMAGE_SIMPLE} // 使用 Ant Design 提供的简约图标
                                    // description={emptyText} // 自定义提示字符
                                    />
                                )
                            }}
                            pagination={{
                                total: count,
                                // pageSize: reqData.MaxResultCount,
                                // onChange: onPageChange
                                current: reqData.current,
                                pageSize: reqData.pageSize,
                                showSizeChanger: reqData.showSizeChanger,
                                pageSizeOptions: reqData.pageSizeOptions
                            }}
                            onChange={onPageChange} /></ConfigProvider>
                </Card>
            </div>
        </div>
    )
}

export default UserList